package cn.gwm.flink.streaming.function.process;

import cn.gwm.flink.streaming.beans.estimateSoh.EstimateSohRecord;
import cn.gwm.flink.streaming.constant.DefaultConstant;
import cn.gwm.flink.streaming.dwm.charge.util.ModeCodeUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * soh估算数据预处理
 *
 * @author GW00283474
 */
public class EstimateSohPrehandleMapFunction implements MapFunction<String, EstimateSohRecord> {
    private static final Logger logger = LoggerFactory.getLogger(EstimateSohPrehandleMapFunction.class);
    @Override
    public EstimateSohRecord map(String s) {
        try {
            Date date = new Date();
            EstimateSohRecord estimateSohRecord = JSONUtil.toBean(s, EstimateSohRecord.class);
            if(Objects.isNull(estimateSohRecord.getModel_name())){
                estimateSohRecord.setModel_name("暂无匹配");
            }
            if(Objects.isNull(estimateSohRecord.getVehicletype())){
                estimateSohRecord.setVehicletype("暂无匹配");
            }
            if(Objects.isNull(estimateSohRecord.getLicense_plate())){
                estimateSohRecord.setLicense_plate("暂无匹配");
            }
            if(Objects.isNull(estimateSohRecord.getCell_battery_type())|| DefaultConstant.Cell_Battery_Type.equals(estimateSohRecord.getCell_battery_type())){
                Map<String, String> batteryData = ModeCodeUtil.batteryData(estimateSohRecord.getDeviceId());
                if(CollectionUtil.isNotEmpty(batteryData)){
                    estimateSohRecord.setCell_battery_type(batteryData.getOrDefault("cellBatteryType",DefaultConstant.Cell_Battery_Type));
                }else{
                    logger.error("数据：{}，暂未查到电池类型信息！",JSONUtil.toJsonStr(estimateSohRecord));
                    estimateSohRecord.setCell_battery_type(DefaultConstant.Cell_Battery_Type);
                }
            }
            //填充摄入时间
            estimateSohRecord.setIngestionDate(DateUtil.format(date, DatePattern.NORM_DATE_PATTERN));
            estimateSohRecord.setIngestionTime(DateUtil.format(date, DatePattern.NORM_DATETIME_PATTERN));

            return estimateSohRecord;
        } catch (Exception e) {
            logger.error("异常数据源：{}",s);
            e.printStackTrace();
        }
        return null;
    }
}
